<?php


namespace App\Http\Services\FormBuilder\Segments;

use App\Http\Services\FormBuilder\Elements\Button;
use App\Http\Services\FormBuilder\Elements\Field;

class MoneySelectorBracketNotStockLimit extends BaseMoneySelectorBracket
{
    protected $attributes = [
        'class' => 'fields',
        'id'    => 'goal_options',
    ];


    public function render()
    {
        if ($girdWidth = $this->getGirdWidth()) {
            $this->addClass($this->normalizeWidth($girdWidth));
        }
        $html = '<div';
        $html .= $this->renderAttributes();
        $html .= '>';
        $hasActiveOption = false;
        if ($this->label) {
            $html .= $this->label;
        }
        $fields = collect($this->brackets)->map(function ($item) use (&$hasActiveOption) {
            $value  = $item['money'] . ' ' . $this->unit;
            $button = new Button($value);
            $button->addClass('no-mobile-hover needsclick money-option')
                ->data('money', $item['money'])
                ->data('bracket-id', $item['id'])
                ->data('desc', $item['desc']);
            if ($item['money'] == $this->defaultMoney && !$hasActiveOption) {
                $button->addClass('active');
                $hasActiveOption = true;
            }
            $field = new Field($button);
            return $field;
        })->all();
        foreach ($fields as $field) {
            $html .= $field;
        }
        $html .= '</div>';

        return $html;
    }

    private function getGirdWidth()
    {
        $countBrackets = count($this->brackets);
        if ($countBrackets >= 1 && $countBrackets < 4) {
            return $countBrackets;
        }
        if ($countBrackets >= 4) {
            $maxMoney = collect($this->brackets)->max('money');
            if ($maxMoney > 9999 || $this->interval) {
                return 3;
            } else {
                return 4;
            }
        }

        return 0;
    }
}